package example;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.logging.Logger;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;



public class GenerateJavaSourceApi {
	final static Logger logger = Logger.getLogger(CompilerAPITest.class.getName()) ;
	public static String EST_SPRING_MVC = "src/main/java";
	public static String CARPETA_DOMINIO = "dominio";
	public static String CARPETA_UTIL = "util";
	public static String CARPETA_DAO = "dao";
	public static String CARPETA_DAO_BASE = "dao/base";
	public static String CARPETA_DAO_IMPL = "dao/impl";
	
	public GenerateJavaSourceApi(String proyecto, String packBase) throws Exception {
		
		String pathProject = getPahProject(1, proyecto);
		String pathJavaProject = pathProject+File.separator+EST_SPRING_MVC;
		String findCarpetaDominio = pathProject+File.separator+EST_SPRING_MVC+File.separator+packBase+File.separator+CARPETA_DOMINIO;
		{
			String entidad="Entidad";
			String findCarpetaUtil = pathProject+File.separator+EST_SPRING_MVC+File.separator+packBase+File.separator+CARPETA_UTIL;
			File fileUtil = new File(findCarpetaUtil);
			if(!fileUtil.exists()){
				throw new Exception("No existe la carpeta de Util en:"+findCarpetaUtil);
			}
			System.out.println("Si existe la carpeta Util");	
		}
		{
			String findCarpetaDAO = pathProject+File.separator+EST_SPRING_MVC+File.separator+packBase+File.separator+CARPETA_DAO;
			File fileDAO = new File(findCarpetaDAO);
			if(!fileDAO.exists()){
				fileDAO.mkdir();
				System.out.println("Creada la carpeta DAO");
			}
		}
		File fileDominio = new File(findCarpetaDominio);
		if(!fileDominio.exists()){
			throw new Exception("No existe la carpeta de Domino en:"+fileDominio);
		}
		System.out.println();
		System.out.println("Si existe la carpeta Domino");	
		File[] entidadesFile = fileDominio.listFiles();
		String strName = "";
		for (int i = 0; i < entidadesFile.length; i++) {
			strName = entidadesFile[i].getName();
			System.out.println(strName);
			if(strName.endsWith(".java")){
				cargarEntidad(pathJavaProject,packBase+"/"+CARPETA_DOMINIO,entidadesFile[i].getName(),strName.substring(0, (strName.indexOf("."))) );				
			}
		}
		
	
		System.out.println("Si existe la carpeta DAO");
		String findCarpetaDAOBASE = pathProject+File.separator+EST_SPRING_MVC+File.separator+packBase+File.separator+CARPETA_DAO_BASE;
		File fileDAOBASE = new File(findCarpetaDAOBASE);
		if(!fileDAOBASE.exists()){
			fileDAOBASE.mkdir();
			System.out.println("Creada la carpeta DAO BASE");
		}
		System.out.println("Si existe la carpeta DAO BASE");
		String findCarpetaDAOIMPL = pathProject+File.separator+EST_SPRING_MVC+File.separator+packBase+File.separator+CARPETA_DAO_IMPL;
		File fileDAOIMPL = new File(findCarpetaDAOIMPL);
		if(!fileDAOIMPL.exists()){
			fileDAOIMPL.mkdir();
			System.out.println("Creada la carpeta DAO IMPL");
		}
		System.out.println("Si existe la carpeta DAO IMPL");		
	}
	
	private void cargarEntidad(String pathProject, String packBase,  String entidad, String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
		System.out.println("----------------cargarEntidad--------------------------");
		String packBaseEnt = packBase+"/"+className;
		packBaseEnt = packBaseEnt.replaceAll("/", ".");
		packBase = packBase+"/"+entidad;		
		try {
			File root = new File(pathProject);
//			File sourceFile = new File(root, packBase);				
//			JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//			compiler.run(null, null, null, sourceFile.getPath());
//			System.out.println(root.toURI().toURL());
			 
			URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL()  });
			Class<?> cls = Class.forName(packBaseEnt, true, classLoader);
			Object instance = cls.newInstance(); 
			System.out.println(instance);
//			EntidadesReader reader = new EntidadesReader(instance);
//			reader.validarEstructuraEntidad(pathProject,packBase,entidad,className);
//			if(reader.isValid()){
//				reader.generateDAOBASE(pathProject,packBase,entidad,className);
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}				
		System.out.println("----------------cargarEntidad--------------------------");
	}
	
	public static void main(String[] args) {		
		try {
			new GenerateJavaSourceApi("test","com/test");	
		} catch (Exception e) {
			e.printStackTrace();
		}			
	}

	public static String getPahProject(int tipo, String nombreProyect) throws Exception {
        URL location = GenerateJavaSourceApi.class.getProtectionDomain().getCodeSource().getLocation();
        String pathProject = location.getFile();        
        pathProject = pathProject.substring(1, pathProject.lastIndexOf("/JavaCompilerAPI"))+File.separator+nombreProyect;
              
		if(tipo==1){ // tipo Spring mvc
			 return pathProject;
		}
		if(tipo==2){ // tipo Liferay Spring Portlet mvc
			
		}
        return "";
    }
	
}
////Prepare source somehow.
//String source = "package test; public class Test { static { System.out.println(\"hello\"); } public Test() { System.out.println(\"world\"); } }";
//
////Save source in .java file.
//File root = new File("/java"); // On Windows running on C:\, this is C:\java.
//File sourceFile = new File(root, "test/Test.java");
//sourceFile.getParentFile().mkdirs();
//new FileWriter(sourceFile).append(source).close();
//
////Compile source file.
//JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
//compiler.run(null, null, null, sourceFile.getPath());
//
////Load and instantiate compiled class.
//URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
//Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello".
//Object instance = cls.newInstance(); // Should print "world".
//System.out.println(instance); // Should print "test.Test@hashcode".